//
//  JJAssetDedup2.swift
//  JJAlbumFramework
//
//  Created by 吴梓杭 on 2025/10/18.
//

import Foundation
import Photos

class JJAssetDeduplicator: NSObject {
    public var uploadedRecords = Set<String>()
    private let lock = NSLock()
    public var assetIDCache: [String: String] = [:] // asset.localIdentifier -> uniqueID
    
    // 预加载所有需要检查的资源的ID，带进度回调
    func preloadAssetIDs(_ assets: [PHAsset],
                        progress: ((Float) -> Void)? = nil,
                        completion: @escaping () -> Void) {
        DispatchQueue.global(qos: .userInitiated).async {
            let group = DispatchGroup()
            let totalCount = assets.count
            var completedCount = 0
            let progressLock = NSLock()
            var lastReportedPercentage = -1 // 记录上次报告的百分比
            
            for asset in assets {
                group.enter()
                generateUniqueID(asset: asset) { uniqueID in
                    self.lock.lock()
                    self.assetIDCache[asset.localIdentifier] = uniqueID
                    self.lock.unlock()
                    
                    // 更新进度
                    progressLock.lock()
                    completedCount += 1
                    let currentProgress = Float(completedCount) / Float(totalCount)
                    let currentPercentage = Int(currentProgress * 100)
                    progressLock.unlock()
                    
                    // 只有当百分比变化时才回调
                    if currentPercentage != lastReportedPercentage {
                        lastReportedPercentage = currentPercentage
                        DispatchQueue.main.async {
                            progress?(currentProgress)
                        }
                    }
                    
                    group.leave()
                }
            }
            
            group.wait()
            
            // 确保100%被回调
            DispatchQueue.main.async {
                progress?(1.0)
//                let array = ((self.assetIDCache as NSDictionary).allValues as NSArray).componentsJoined(by: ",")
//                print(array)
                completion()
            }
        }
    }
    
    func shouldUpload(_ asset: PHAsset) -> Bool {
        lock.lock()
        defer { lock.unlock() }
        
        guard let uniqueID = assetIDCache[asset.localIdentifier] else {
            print("Warning: Asset ID not preloaded for \(asset.localIdentifier)")
            return true
        }
        
        let shouldUpload = !uploadedRecords.contains(uniqueID)
        print("Asset ID: \(uniqueID), shouldUpload: \(shouldUpload)")
        return shouldUpload
    }
    
    func markAsUploaded(_ asset: PHAsset) {
        lock.lock()
        defer { lock.unlock() }
        
        if let uniqueID = assetIDCache[asset.localIdentifier] {
            uploadedRecords.insert(uniqueID)
        }
    }
    
    // 批量标记为已上传，带进度回调
    func markAssetsAsUploaded(_ assets: [PHAsset],
                             progress: ((Float) -> Void)? = nil,
                             completion: @escaping () -> Void) {
        DispatchQueue.global(qos: .userInitiated).async {
            let totalCount = assets.count
            var completedCount = 0
            let progressLock = NSLock()
            var lastReportedPercentage = -1
            
            for asset in assets {
                self.lock.lock()
                if let uniqueID = self.assetIDCache[asset.localIdentifier] {
                    self.uploadedRecords.insert(uniqueID)
                }
                self.lock.unlock()
                
                // 更新进度
                progressLock.lock()
                completedCount += 1
                let currentProgress = Float(completedCount) / Float(totalCount)
                let currentPercentage = Int(currentProgress * 100)
                progressLock.unlock()
                
                // 只有当百分比变化时才回调
                if currentPercentage != lastReportedPercentage {
                    lastReportedPercentage = currentPercentage
                    DispatchQueue.main.async {
                        progress?(currentProgress)
                    }
                }
            }
            
            // 确保100%被回调
            DispatchQueue.main.async {
                progress?(1.0)
                completion()
            }
        }
    }
    
    // 获取需要上传的资源列表，带进度回调
    func getAssetsToUpload(_ assets: [PHAsset],
                          progress: ((Float) -> Void)? = nil,
                          completion: @escaping ([PHAsset]) -> Void) {
        var assetsToUpload: [PHAsset] = []
        let assetsLock = NSLock()
        
        DispatchQueue.global(qos: .userInitiated).async {
            let totalCount = assets.count
            var processedCount = 0
            let progressLock = NSLock()
            let group = DispatchGroup()
            var lastReportedPercentage = -1
            
            for asset in assets {
                group.enter()
                
                // 检查是否需要上传
                let shouldUpload = self.shouldUpload(asset)
                
                assetsLock.lock()
                if shouldUpload {
                    assetsToUpload.append(asset)
                }
                assetsLock.unlock()
                
                // 更新进度
                progressLock.lock()
                processedCount += 1
                let currentProgress = Float(processedCount) / Float(totalCount)
                let currentPercentage = Int(currentProgress * 100)
                progressLock.unlock()
                
                // 只有当百分比变化时才回调
                if currentPercentage != lastReportedPercentage {
                    lastReportedPercentage = currentPercentage
                    DispatchQueue.main.async {
                        progress?(currentProgress)
                    }
                }
                
                group.leave()
            }
            
            group.wait()
            
            // 确保100%被回调
            DispatchQueue.main.async {
                progress?(1.0)
                completion(assetsToUpload)
            }
        }
    }
    
    // 获取当前缓存状态
    var cachedAssetsCount: Int {
        lock.lock()
        defer { lock.unlock() }
        return assetIDCache.count
    }
    
    var uploadedAssetsCount: Int {
        lock.lock()
        defer { lock.unlock() }
        return uploadedRecords.count
    }
}
